package com.bieber.common;

import java.lang.reflect.Method;
import java.util.Properties;

/**
 * Created by bieber on 2015/8/20.
 */
public abstract class AbstractConfig {

    public void loadFromProperties(Properties properties){
        Method[] methods = this.getClass().getDeclaredMethods();
        for(Method method:methods){
            String methodName = method.getName();
            if(methodName.startsWith("set")&&methodName.length()>3){
                String propertyName = methodName.substring(3,4).toLowerCase()+methodName.substring(4);
                Class<?>[] types = method.getParameterTypes();
                if(types!=null&&types.length==1&&properties.containsKey(propertyName)){
                    Class<?> type =types[0];
                    Object arg=properties.get(propertyName);
                    if(Integer.class==type||Integer.TYPE==type){
                        arg=Integer.parseInt(arg.toString());
                    }else if(Long.class==type||Long.TYPE == type){
                        arg=Long.parseLong(arg.toString());
                    }else if(Short.class == type||Short.TYPE == type){
                        arg=Short.parseShort(arg.toString());
                    }else if(String.class==type){
                        arg=arg.toString();
                    }else if(Double.class==type || Double.TYPE == type){
                        arg=Double.parseDouble(arg.toString());
                    }else if(Float.class==type||Float.TYPE == type){
                        arg=Float.parseFloat(arg.toString());
                    }
                    try {
                        method.invoke(this,new Object[]{arg});
                    } catch (Throwable e) {
                    }
                }
            }
        }
    }
}
